<?php

namespace addons\JhxEdu\services\product;

use addons\JhxEdu\common\enums\AccessTokenGroupEnum;
use addons\JhxEdu\common\models\order\Order;
use common\helpers\EchantsHelper;
use Yii;
use yii\data\Pagination;
use yii\db\ActiveQuery;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use common\helpers\ArrayHelper;
use common\components\Service;
use common\enums\WhetherEnum;
use common\enums\StatusEnum;
use common\helpers\StringHelper;
use common\helpers\BcHelper;
use common\helpers\AddonHelper;
use addons\JhxEdu\common\models\SettingForm;
use addons\JhxEdu\common\models\order\OrderProduct;
use addons\JhxEdu\common\models\product\Product;
use addons\JhxEdu\common\models\product\ProductContent;
use addons\JhxEdu\common\models\base\Spec;

/**
 * Class ProductService
 * @package addons\JhxEdu\services\product
 * @author jianyan74 <751393839@qq.com>
 */
class ProductService extends Service
{
    /**
     * 获取猜你喜欢的课程
     *
     * @param $member_id
     * @return mixed|\yii\db\ActiveRecord
     */
    public function getGuessYouLike($member_id)
    {
        $cates = Yii::$app->tinyShopService->memberFootprint->findCateIdsByMemberId($member_id);

        $data = Product::find()
            ->where(['status' => StatusEnum::ENABLED, 'product_status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->andFilterWhere(['in', 'cate_id', $cates]);
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => 10, 'validatePage' => false]);
        $models = $data->offset($pages->offset)
            ->orderBy('rand()')
            ->select([
                'id',
                'name',
                'sketch',
                'keywords',
                'picture',
                'view',
                'star',
                'price',
                'market_price',
                'cost_price',
                'stock',
                'real_sales',
                'sales',
                'merchant_id',
                'is_open_presell',
                'is_open_commission',
                'point_exchange_type',
                'point_exchange',
                'max_use_point',
                'integral_give_type',
                'give_point',
            ])
            ->asArray()
            ->limit($pages->limit)
            ->all();

        foreach ($models as &$model) {
            $model['sales'] = $model['sales'] + $model['real_sales'];
            unset($model['real_sales']);
        }

        return $models;
    }

    /**
     * @param ProductSearch $search
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getListBySearch(Product $search)
    {
        $order = ['sort asc', 'id desc'];

        // 所有下级分类
        $cate_ids = [];
        if ($cate_id = $search->cate_id) {
            $cate_ids = Yii::$app->jhxEduService->productCate->findChildIdsById($cate_id);
        }
        
        $data = Product::find()
            ->where(['status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->andFilterWhere(['like', 'name', $search->keyword])
            ->andFilterWhere(['is_top' => $search->is_top])
            ->andFilterWhere(['product_status' => $search->product_status])
            ->andFilterWhere(['in', 'cate_id', $cate_ids])
            ->with('cate');
        if(is_array($search->real_price)){
            $data ->andFilterWhere(['between','real_price',$search->real_price[0], $search->real_price[1]]);
        }else{
            $data ->andFilterWhere(['real_price' => $search->real_price]);
        }    
        $pages = new Pagination([
            'totalCount' => $data->count(),
            'pageSize' => $search->page_size,
            'validatePage' => false,
        ]);
        $models = $data->offset($pages->offset)
            ->orderBy(implode(',', $order))
            ->select([
                'id',
                'cate_id',
                'name',
                'real_price',
                'market_price',
                'virtual_sale',
                'picture',
            ])
            ->asArray()
            ->limit($pages->limit)
            ->all();
        foreach ($models as $key => $value) {
            if($models[$key]['picture']){
                $models[$key]['thumb'] = StringHelper::getThumbUrl($models[$key]['picture'], 600, 400);
            }
            
        }
        return $models;
    }
    /**
     * 评论数量改变
     *
     * @param $product_id
     * @param int $scores
     * @param int $num
     */
    public function commentNumChange($product_id, $scores = 5, $num = 1)
    {
        $product = $this->findById($product_id);
        $product->comment_num += $num;

        $star = $product->star + $scores;
        $match_point = $star / ($product->comment_num + 1);
        $match_ratio = ($match_point / 5) * 100;

        $product->star = $star;
        $product->match_point = $match_point;
        $product->match_ratio = $match_ratio;
        $product->save();
    }

    /**
     * 绑定营销
     *
     * @param $product_ids
     * @param int $scores
     * @param int $num
     */
    public function bindingMarketing($product_ids, $marketing_id, $marketing_type)
    {
        Product::updateAll(['marketing_id' => $marketing_id, 'marketing_type' => $marketing_type], ['in', 'id', $product_ids]);
        // 触发购物车失效
        Yii::$app->tinyShopService->memberCartItem->loseByProductIds($product_ids);
    }

    /**
     * @param string $keyword
     * @return array
     */
    public function getList($keyword = '')
    {
        $data = Product::find()
            ->where(['status' => StatusEnum::ENABLED, 'product_status' => StatusEnum::ENABLED])
            ->andFilterWhere(['like', 'name', $keyword])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()]);
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => 10]);
        $models = $data->offset($pages->offset)
            ->orderBy('sort asc, id desc')
            ->select(['id', 'name','real_price'])
            ->asArray()
            ->limit($pages->limit)
            ->all();

        foreach ($models as &$model) {
            $model['covers'] = unserialize($model['covers']);
        }
        return [$models, $pages];
    }

    /**
     * @param $id
     * @return array|\yii\db\ActiveRecord|null
     */
    public function findById($id)
    {
        return Product::find()
            ->where(['id' => $id, 'status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->one();
    }
    /**
     * @param $id
     * @param $member_id
     * @return array|\yii\db\ActiveRecord|null
     * @throws NotFoundHttpException
     */
    public function findViewById($id, $member_id)
    {
        $model = Product::find()
            ->where(['id' => $id, 'product_status' => StatusEnum::ENABLED])
            ->andWhere(['>=', 'status', StatusEnum::DISABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->with(['data'])
            ->with([
                'myCollect' => function (ActiveQuery $query) use ($member_id) {
                    return $query->andWhere(['member_id' => $member_id]);
                }
            ])
            ->asArray()
            ->one();
        if (!$model) {
            throw new NotFoundHttpException('找不到该产品');
        }
        $model['content_count'] = $this->contentCount($model['id']);
        if($model['cover']){
            $model['cover'] = unserialize($model['cover']);
        }
        
        
        return $model;
    }
  
    public function contentCount($product_id){
       return  ProductContent::find()->where(['status'=>1,'product_id'=>$product_id])->count();
    }
    public function buyed($product_id){
        $member_id = !Yii::$app->user->isGuest ? Yii::$app->user->identity->member->id : '';
        if(!$member_id){
            return false;
        }
        if(!$product_id){
            return false;
        }
        $model =  OrderProduct::find()->where(['product_id'=>$product_id,'member_id'=>$member_id])->one();
        if(!$model || !$model->product_id){
            return false;
        }
        return true;
       
    }
    /**
     * 获取销量排名
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getRank($limit = 8)
    {
        return Product::find()
            ->where(['status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->orderBy('real_sales desc')
            ->limit($limit)
            ->asArray()
            ->all();
    }
    /**
     * @param $ids
     * @return array|\yii\db\ActiveRecord|null
     */
    public function findByIds($ids)
    {
        return Product::find()
            ->where(['status' => StatusEnum::ENABLED, 'product_status' => StatusEnum::ENABLED])
            ->andWhere(['in', 'id', $ids])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->orderBy('id asc')
            ->all();
    }
}